package com.sinosoft.sm.system.common.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 对象处理工具类
 * @author xiaoxiong
 *
 */
public class ObjectUtil {

	/**
	 * 将对象ObjectFrom属性值赋值给ObjectTo
	 * @param objectTo	被赋值的对象
	 * @param objectFrom	赋值的对象
	 * @param args	不被赋值的属性
	 */
	public static void oldToNew(Object objectTo, Object objectFrom, String... args){
		Field[] fieldsFrom = objectFrom.getClass().getDeclaredFields();
		Field[] fieldsTo = objectTo.getClass().getDeclaredFields();
		for(int i=0; i<fieldsTo.length; i++) {
			Boolean isContinue = true;
			for(String arg : args) {
				if(arg.equals(fieldsTo[i].getName())) {
					isContinue = false;
					break;
				}
			}
			if(!isContinue) {
				continue;
			}
			for(int j=0; j<fieldsFrom.length; j++) {
				if(fieldsTo[i].getName().equals(fieldsFrom[j].getName())) {
					PropertyDescriptor pdTo = null;
					try {
						pdTo = new PropertyDescriptor(fieldsTo[i].getName(), objectTo.getClass());
					} catch (IntrospectionException e) {
						e.printStackTrace();
					}
					PropertyDescriptor pdFrom = null;
					try {
						pdFrom = new PropertyDescriptor(fieldsFrom[j].getName(), objectFrom.getClass());
					} catch (IntrospectionException e) {
						e.printStackTrace();
					}
					try {
						pdTo.getWriteMethod().invoke(objectTo, pdFrom.getReadMethod().invoke(objectFrom));
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
